package com.icim.cxbh.export.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.icim.cxbh.export.pojo.BoxInfo;
import com.icim.cxbh.export.pojo.EaInfo;
import com.icim.cxbh.export.pojo.OqcInfo;

@Service("dataImportService")
@Transactional("cxbhTransactionManager")
public class DataImportServiceImpl implements DataImportService {

	private static final Logger LOGGER = Logger
			.getLogger(DataImportServiceImpl.class);

	@Resource
	private JdbcTemplate cxbhJdbcTemplate;

	@Override
	public void importData(OqcInfo oqcInfo) {

		List<Object[]> oqcInfoBatch = new ArrayList<Object[]>();
		List<Object[]> oqcEaInfoBatch = new ArrayList<Object[]>();
		List<Object[]> iqcEaInfoBatch = new ArrayList<Object[]>();

		List<BoxInfo> boxInfoList = oqcInfo.getBoxInfoList();

		String oqcInfoSql = "insert into OQC_INFO (BOX_ID, MODEL, WORK_QTY, STKIN_DATE) values (?, ?, ?, ?)";
		String oqcEaInfoSql = "insert into OQC_EA_INFO (BOX_ID, EA_ID) values (?, ?)";
		String iqcEaInfoSql = "insert into IQC_EA_INFO (EA_ID, MODEL, INPUT_DATE) values (?, ?, ?)";

		for (BoxInfo boxInfo : boxInfoList) {
			
			LOGGER.info("Import box " + boxInfo.getBoxId());

			oqcInfoBatch.add(new Object[] { boxInfo.getBoxId(),
					boxInfo.getModel(), boxInfo.getWorkQty(),
					boxInfo.getStkinDate() });

			List<EaInfo> eaInfos = boxInfo.getEaInfos();
			
			for (EaInfo eaInfo : eaInfos) {
				oqcEaInfoBatch.add(new Object[] { boxInfo.getBoxId(),
						eaInfo.getEaId() });
				iqcEaInfoBatch.add(new Object[] { eaInfo.getEaId(),
						boxInfo.getModel(), boxInfo.getStkinDate() });

			}
		}
		
		cxbhJdbcTemplate.batchUpdate(oqcInfoSql, oqcInfoBatch);
		cxbhJdbcTemplate.batchUpdate(oqcEaInfoSql, oqcEaInfoBatch);
		cxbhJdbcTemplate.batchUpdate(iqcEaInfoSql, iqcEaInfoBatch);

	}

}
